// pages/index/goods/goods.js

const UPDATE_GOING_ORDER_COUNT_GAP = 20 * 1000;
const MAX_PAGE_COUNT = 30
const DEFAULT_CROP_ID = "0"
const DEFAULT_GOOD_TYPE_ID = "0"

var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var emptyUtil = require('../../templates/empty/empty.js')
const app = getApp()
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    identity:null,

    nextRequestGoingCountTime: 0, //下次请求更新正在进行中的订单数量时间戳
    goingOrderCount: null, //正在进行中的订单数量

    // cropList: null, //作物分类
    cropMyList: [{
      "cropId": DEFAULT_CROP_ID,
      "cropName": "我的作物",
      "isMyCrop": "1"
    }], //我的作物列表
    cropMoreList: [], //更多作物列表
    curTopBarIndex: 0, //顶部tabBar当前位置

    goodTypeList: [],//商品种类列表
    goodChildTypeList:[],//商品子标签列表
    goodTypeBarIndex: 0,
    goodChildTypeBarIndex:0,

    goodsList: null, //商品列表
    requestGoodsTask: null, //请求task

    searchGoodParam: { //搜索条件
      "cropId": DEFAULT_CROP_ID,
      "orderBy": null,
      "sort": null,
      "pageNum": 0,
      "pageRows": MAX_PAGE_COUNT,
    },
    enableLoadMore: true,
    isLoadingMore: false,

    topWarnText: "提示：近期是被旺季配送压力较大，建议提前三天下单，以免延误施肥时机。",
    topWarnShow: false, //是否显示顶部消息提醒

    emptyParam: {},

  


    showConfirmDialog: false, //是否显示
    confirmDialogCount: 1, //初始数量
    confirmDialogType: 1, //1:加入购物车 2：立即购买
    confirmDialogGood: {}, //确认框显示的商品信息
    dialogInputFocus: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    uiUtil.showLoading("正在加载..")
    //获取作物分类
    that.requestCropList()
    //获取商品种类
    that.requestGoodTypeList(DEFAULT_GOOD_TYPE_ID)
    //获取我的作物对应商品
    that.requestGoodsList(DEFAULT_CROP_ID, DEFAULT_GOOD_TYPE_ID);
    that.setData({
      identity:app.globalData.identity
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //获取全局变量
    var cardCount = app.globalData.cartCount
    if (cardCount) {
      this.setData({
        'goingOrderCount.cardCount': cardCount
      })
    }


    //更新未完成订单数量
    var curTime = new Date().getTime();
    if (curTime > that.data.nextRequestGoingCountTime) {
      //更新
      that.setData({
        nextRequestGoingCountTime: curTime + UPDATE_GOING_ORDER_COUNT_GAP
      })
      //请求数据
      that.requestGoingOrderCount();
    }
  },
  /**
   * 滑动到底部
   */
  onReachBottom: function() {
    this.requestGoodsList(this.data.searchGoodParam.cropId, this.data.searchGoodParam.goodTypeId)
  },
  onShareAppMessage: function(res) {
    return util.handleShareApp()
  },

  /**
   * 获取正在进行中的订单数据
   */
  requestGoingOrderCount() {
    httpUtil.PostRequest("going_order_count", {}, {
      success(res) {
        that.setData({
          goingOrderCount: res
        })
        //更新全局变量
        if (res.cardCount) {
          app.resetCartCount(res.cardCount)
        }
      },
      fail(code, res) {},
      complete() {
        uiUtil.hideLoading()
      }
    })
  },

  /**
   * 获取作物分类列表
   */
  requestCropList() {
    httpUtil.PostRequest("crop_list", {}, {
      success(res) {
        var listLength = res.length;

        if (listLength == 0) { //列表为空
          return;
        }
        var myCropList = that.data.cropMyList;
        var moreCropList = that.data.cropMoreList;
        for (var i = 0; i < listLength; i++) {
          var item = res[i];
          if (item.isMyCrop == '1') {
            myCropList.push(item)
          } else {
            moreCropList.push(item)
          }
        }
        that.setData({
          cropMyList: myCropList,
          cropMoreList: moreCropList
        })
      },
      fail(code, res) {},
      complete() {}
    })
  },

  /**
   * 获取商品种类列表
   */
  requestGoodTypeList(goodTypeId) {
    httpUtil.PostRequest("good_type_list", {
      goodTypeId: goodTypeId
    }, {
      success(res) {
        var listLength = res.length;
        if (listLength == 0) { //列表为空
          return;
        }
        var goodTypeList = res
        var allType = {
          goodTypeId: DEFAULT_GOOD_TYPE_ID,
          goodTypeName: '全部'
        }
        goodTypeList.unshift(allType)
        that.setData({
          goodTypeList: goodTypeList,
        })
      },
      fail(code, res) { },
      complete() { }
    })
  },

  /**
   * 获取商品子标签列表
   */
  requestGoodChildTypeList(goodTypeId) {
    httpUtil.PostRequest("good_type_list", {
      goodTypeId: goodTypeId
    }, {
        success(res) {
          var listLength = res.length;
          if (listLength == 0) { //列表为空
            return;
          }
          var goodChildTypeList = res
          var allType = {
            goodTypeId: goodTypeId,
            goodTypeName: '全部'
          }
          goodChildTypeList.unshift(allType)
          that.setData({
            goodChildTypeList: goodChildTypeList,
          })
        },
        fail(code, res) { },
        complete() { }
      })
  },


  /**
   * 获取商品列表
   */
  requestGoodsList(cropId,goodTypeId) {
    var lastRequestTask = this.data.requestGoodsTask;
    if (lastRequestTask) {
      try {
        lastRequestTask.abort()
      } catch (e) {}
    }

    var curPage = that.data.searchGoodParam.pageNum

    if (curPage != 0 && (!that.data.enableLoadMore || that.data.isLoadingMore)) { //不可加载||正在加载
      return;
    }

    this.setData({
      isLoadingMore: true,
      'searchGoodParam.pageNum': curPage + 1,
      'searchGoodParam.cropId': cropId,
      'searchGoodParam.goodTypeId': goodTypeId,
    })
    var requestTask = httpUtil.PostRequest("search_goods_list", that.data.searchGoodParam, {
      complete() {
        wx.hideLoading()
        that.setData({
          isLoadingMore: false
        })
      },
      success(res) {
        var datalist;
        if (1 == that.data.searchGoodParam.pageNum) {
          datalist = res.goodList || []
          if (datalist.length == 0) { //内容为空
            emptyUtil.showEmptyView()
          } else {
            emptyUtil.hideView()
          }
        } else {
          datalist = that.data.goodsList.concat(res.goodList || [])
        }
        that.setData({
          goodsList: datalist,
          enableLoadMore: datalist.length < res.rowCount,
        })
      },
      fail(code, res) {
        that.setData({
          enableLoadMore: false,
        })
        if (1 == that.data.searchGoodParam.pageNum) { //内容为空
          var text = emptyUtil.getErrText(code, res, "获取商品信息失败")
          emptyUtil.showFailView(text)
        }
      }
    })
    that.setData({
      requestGoodsTask: requestTask
    })
  },

  /**
   * 顶部tabbar点击切换
   */
  swithTabBar(e) {
    var clickIndex = e.target.dataset.current;
    if (this.data.curTopBarIndex == clickIndex) {
      return false;
    } else { //切换选项卡
      var cropId = that.data.cropMyList[clickIndex].cropId

      this.setData({
        enableLoadMore: true,
        curTopBarIndex: clickIndex,
        'searchGoodParam.pageNum': 0,
        goodsList: null,
      })
      that.requestGoodsList(cropId, this.data.searchGoodParam.goodTypeId)
      uiUtil.showLoading("正在加载中...")
    }
  },

  /**
   * 顶部商品分类tabbar点击切换
   */
  swithGoodTypeTabBar(e) {
    var clickIndex = e.target.dataset.current;
    if (this.data.goodTypeBarIndex == clickIndex) {
      return false;
    } else { //切换选项卡
      var goodTypeId = that.data.goodTypeList[clickIndex].goodTypeId

      this.setData({
        enableLoadMore: true,
        goodTypeBarIndex: clickIndex,
        'searchGoodParam.pageNum': 0,
        goodsList: null,
        goodChildTypeBarIndex:"0"
      })
      if (clickIndex==0){
        that.setData({
          goodChildTypeBarIndex:"0",
          goodChildTypeList:null
        })
      } else {
        that.requestGoodChildTypeList(goodTypeId);
      }
      that.requestGoodsList(this.data.searchGoodParam.cropId, goodTypeId)
      uiUtil.showLoading("正在加载中...")
      
    }
  },

  /**
   * 顶部商品子标签分类tabbar点击切换
   */
  swithGoodChildTypeTabBar(e) {
    var clickIndex = e.target.dataset.current;
    var goodTypeId = e.target.dataset.goodtypeid;
    
    if (this.data.goodChildTypeBarIndex == clickIndex) {
      return false;
    } else { //切换选项卡

      this.setData({
        enableLoadMore: true,
        goodChildTypeBarIndex: clickIndex,
        'searchGoodParam.pageNum': 0,
        goodsList: null,
      })
      that.requestGoodsList(this.data.searchGoodParam.cropId, goodTypeId)
      uiUtil.showLoading("正在加载中...")

    }
  },


  //==============弹出框确认==============
  /**
   * 添加商品进入购物车
   */
  addCartClick(e) {
    var index = e.currentTarget.dataset.index
    var goodInfo = this.data.goodsList[index]
    this.setData({
      confirmDialogGood: goodInfo,
      confirmDialogCount: 1
    })
    this.showConfirmDialog()

  },

  addCartClickConfirm() {
    var count = this.data.confirmDialogCount
    if (count <= 0) {
      uiUtil.showToast("请选择数量")
      return;
    }

    var goodId = this.data.confirmDialogGood.goodId
    var skuId = this.data.confirmDialogGood.skuId
    httpUtil.PostRequest("add_good_to_card", {
      goodId: goodId,
      skuId: skuId,
      buyCount: count
    }, {
      success(res) {
        that.hideConfirmDialog()
        uiUtil.showToast("添加购物车成功")
        app.cartSelectsAdd(goodId, skuId)
        if (res.cartCount) {
          that.setData({
            'goingOrderCount.cardCount': res.cartCount
          })
          //更新全局变量
          app.resetCartCount(res.cartCount)
        }
      },
      fail(code, res) {
        uiUtil.showToast(res || "添加购物车失败")
      },
      complete() {}
    })
  },

  /* 点击减号 */
  onConfirmDialogCut: function() {
    var confirmDialogCount = this.data.confirmDialogCount || 0;
    // 如果大于1时，才可以减  
    if (confirmDialogCount <= 1) { //原数量为0
      return;
    } else {
      var confirmDialogCount = confirmDialogCount - 1
      this.setData({
        confirmDialogCount: confirmDialogCount,
      });
    }
  },
  /* 点击加号 */
  onConfirmDialogAdd: function() {
    var confirmDialogCount = this.data.confirmDialogCount || 0;
    confirmDialogCount++;
    this.setData({
      confirmDialogCount: confirmDialogCount,
    });
  },

  onConfirmDialogInput(e) {
    var count = e.detail.value
    this.setData({
      confirmDialogCount: count
    })
  },

  //显示对话框
  showConfirmDialog: function () {
    that = this;
    that.setData({
      showConfirmDialog: true
    })
  },
  //隐藏对话框
  hideConfirmDialog: function () {
    that = this;
    that.setData({
      showConfirmDialog: false,
      dialogInputFocus: false
    })
  },

  onConfirmDialogInputClick() {
    this.setData({
      dialogInputFocus: true,
    })
  },
  onConfirmDialogBtnClick() {
    if (this.data.confirmDialogType == 1) { //加入购物车
      that.addCartClickConfirm()
    } else {

    }

  },
})